package com.zll.dms.service.impl;

import com.zll.dms.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 邮件服务
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    private static final Executor emailExecutor =Executors.newFixedThreadPool(4);

    @Value("${mail.object.from}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;


    @Override
    public void sendEmail(String toEmail,String subject,String content) {
        log.info("即将进入异步邮件发送。。。。");
        Runnable sendEmailTask = new Runnable() {
            @Override
            public void run() {
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                try {
                    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
                    messageHelper.setFrom(from);
                    messageHelper.setTo(toEmail);
                    messageHelper.setSubject(subject);
                    messageHelper.setText(content, true);
                    javaMailSender.send(mimeMessage);
                    log.info("发送成功。。。。");
                } catch (MessagingException e) {
                    log.error("发送邮件失败请重试");
                }
            }
        };
        emailExecutor.execute(sendEmailTask);
        log.info("异步邮件发送结束。。。。");
    }
}
